﻿using LibraryManagement.Custom_Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;

namespace LibraryManagement.Inventory
{
    public partial class InvBookCopiesAdd : libForm
    {
        private decimal bookId;
        private Search.SrcBookSearch srcBookSearch;
        private LibManagementEntities context;
        private List<decimal> listCopiesBookLibCode;
        private decimal lastLibCode;

        public InvBookCopiesAdd()
        {
            InitializeComponent();
        }

        public InvBookCopiesAdd(decimal bookId, Search.SrcBookSearch srcBookSearch)
        {
            InitializeComponent();
            this.bookId = bookId;
            this.srcBookSearch = srcBookSearch;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!(epBookCopies.GetError(lblCopiesLibCode) == "Lib Codes already Exists. Conflicting Entries in Grid."))
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        var context = new LibManagementEntities();
                        var OBookDetail = context.BookDetails.Single(x => x.Id == bookId);
                        OBookDetail.Copies += Convert.ToInt16(txtCopies.Text);

                        foreach (DataGridViewRow row in dgvBookCodes.Rows)
                        {
                            var OBookCopy = new BookCopy();
                            OBookCopy.BookId = bookId;
                            OBookCopy.LibCode = Convert.ToDecimal(row.Cells["dgvcBookCode"].Value);
                            OBookCopy.UserId = clsStatics.currentUserId;
                            context.BookCopies.Add(OBookCopy);
                        }
                        context.SaveChanges();

                        ts.Complete();
                    }
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void InvBookCopiesAdd_FormClosed(object sender, FormClosedEventArgs e)
        {
            srcBookSearch.Enabled = true;
            srcBookSearch.SetDataGridView();
        }

        private void InvBookCopiesAdd_Load(object sender, EventArgs e)
        {
            context = new LibManagementEntities();
            var OBookDetail = context.BookDetails.Single(x => x.Id == bookId);
            txtTitle.Text = OBookDetail.Title;
            txtAuthor.Text = OBookDetail.Author1;
            txtPublisher.Text = OBookDetail.Publisher;
            txtISBN.Text = OBookDetail.ISBN.ToString();
            txtEdition.Text = OBookDetail.Edition.ToString();
            txtYearOfEdition.Text = OBookDetail.YearOfEdition.ToString();

            var listLibCodes = context.BookCopies.Where(x => x.BookId == bookId).Select(x => x.LibCode).ToList();
            txtExistingCopies.Text = listLibCodes.Count.ToString();
            dgvBookCodesExisting.DataSource = listLibCodes.Select(x => new { BookCodes = x }).ToList();
            listLibCodes.Sort();
            lastLibCode = listLibCodes.Last(); ;

            listCopiesBookLibCode = context.BookCopies.Where(y => y.UserId == clsStatics.currentUserId && y.BookId != bookId).Select(y => y.LibCode).ToList();
        }

        private void txtCopies_TextChanged(object sender, EventArgs e)
        {
            if (txtCopies.Text.Trim() != "")
            {
                var rowCount = dgvBookCodes.Rows.Count;
                var copies = Convert.ToDecimal(txtCopies.Text);

                if (copies > rowCount)
                {
                    var indexAdd = dgvBookCodes.Rows.Add((int)(copies - rowCount));
                    SetCodes();
                }
                else if (copies < rowCount)
                {
                    var remove = rowCount - copies;
                    while (remove > 0)
                    {
                        dgvBookCodes.Rows.RemoveAt((int)copies);
                        remove--;
                    }
                    SetCodes();
                }
                else
                {
                    if (!chbAutoGen.Checked)
                    {
                        foreach (DataGridViewRow row in dgvBookCodes.Rows)
                        {
                            row.Cells["dgvcBookCode"].Value = null;
                        }
                    }
                    else
                    {
                        SetCodes();
                    }
                }
            }
        }

        private void SetCodes()
        {
            if (chbAutoGen.Checked)
            {
                var x = 1;
                foreach (DataGridViewRow row in dgvBookCodes.Rows)
                {
                    var libCode = lastLibCode + x;
                    row.Cells["dgvcBookCode"].Value = libCode;
                    x++;
                }
                CheckForLibCodes();
            }
        }

        private void chbAutoGen_CheckedChanged(object sender, EventArgs e)
        {
            txtCopies_TextChanged(sender, e);
        }

        private void dgvBookCodes_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                CheckForLibCodes();
            }
            catch (Exception ex)
            {
            }
        }

        private void CheckForLibCodes()
        {
            epBookCopies.SetError(lblCopiesLibCode, "");
            foreach (DataGridViewRow row in dgvBookCodes.Rows)
            {
                if (listCopiesBookLibCode.Contains(Convert.ToDecimal(row.Cells["dgvcBookCode"].Value)))
                    epBookCopies.SetError(lblCopiesLibCode, "Lib Codes already Exists. Conflicting Entries in Grid.");
            }
        }
    }
}
